package com.nowoe.mvc.context;

import com.nowoe.core.bean.BeanFactory;
import com.nowoe.core.bean.BeanFactoryImpl;
import com.nowoe.core.processor.AutowiredBeanPostProcessor;
import com.nowoe.core.processor.ResourceBeanPostProcessor;
import com.nowoe.data.io.Resources;
import com.nowoe.data.processor.MapperBeanPostProcessor;
import com.nowoe.data.sqlSession.SqlSession;
import com.nowoe.data.sqlSession.SqlSessionFactory;
import com.nowoe.data.sqlSession.SqlSessionFactoryBuilder;
import com.nowoe.mvc.parse.XMLParser;

import java.io.InputStream;

/**
 * @author 倚栏听风 2023/9/15 14:16
 * Spring 容器
 */
public class WebApplicationContext {
    private String contextConfigLocation;
    private BeanFactory beanFactory = null;

    public BeanFactory getBeanFactory() {
        return beanFactory;
    }

    public WebApplicationContext(String contextConfigLocation) {
        this.contextConfigLocation = contextConfigLocation;
    }

    /**
     * 初始化容器
     */
    public void refresh() {
        String path = contextConfigLocation.split(":")[1];
        //解析xml文件
        String configClassName = XMLParser.getCtxClassName(path, "config");
        try {
            Class<?> configClass = Class.forName(configClassName);
            //初始化data
            String mapperConfig = XMLParser.getCtxClassName(path, "mapperConfig");
            if (mapperConfig != null && !mapperConfig.equals("")) {
                InputStream resourceStream = Resources.getResourceStream(mapperConfig.split(":")[1]);
                //初始化BeanFactory
                beanFactory = new BeanFactoryImpl(configClass);
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceStream);
                SqlSession sqlSession = sqlSessionFactory.openSession();
                beanFactory.replace(sqlSession.getClass().getInterfaces()[0], sqlSession);
                beanFactory.addPostProcessor(new MapperBeanPostProcessor());
                beanFactory.addPostProcessor( new AutowiredBeanPostProcessor());
                beanFactory.addPostProcessor( new ResourceBeanPostProcessor());
            } else {
                beanFactory = new BeanFactoryImpl(configClass, new ResourceBeanPostProcessor(), new AutowiredBeanPostProcessor());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
